home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 5 / Apprentice-Release5.iso / Source Code / Libraries / JPNL Libraries / TwoPlayerClient.java < prev    next >
Text File  |  1996-04-26  |  2KB  |  93 lines

  1. /*
  2.     ©1996 Peter N Lewis <peter@stairways.com.au>
  3. */
  4.  
  5. package au.com.peter.libraries;
  6.  
  7. import java.io.*;
  8. import java.net.*;
  9. import java.lang.*;
  10.  
  11. public class TwoPlayerClient {
  12.  
  13.     public static final int DEFAULT_PORT = 1465;
  14.     
  15.     private Socket conn = null;
  16.     private DataInputStream sin = null;
  17.     private DataOutputStream sout = null;
  18.     
  19.     
  20.     public TwoPlayerClient( String host ) throws Exception {
  21.         this( host, DEFAULT_PORT );
  22.     }
  23.  
  24.  
  25.     public TwoPlayerClient( String host, int port ) throws Exception {
  26.         if ( port == 0 ) {
  27.             port = DEFAULT_PORT;
  28.         }
  29.         
  30.         try {
  31.             conn = new Socket(host, port);
  32.             sin = new DataInputStream(conn.getInputStream());
  33.             sout = new DataOutputStream(new BufferedOutputStream(conn.getOutputStream())); 
  34.         } catch (Exception e) {
  35.             close();
  36.             throw e;
  37.         }
  38.  
  39.  
  40.     }
  41.     
  42.  
  43.     protected void finalize() {
  44.         close();
  45.     }
  46.     
  47.     
  48.     public void close() {
  49.         sin = null;
  50.         sout = null;
  51.         if ( conn != null ) {
  52.             try {
  53.                 conn.close();
  54.             } catch (IOException e2) {
  55.             }
  56.         }
  57.         conn = null;
  58.     }
  59.     
  60.     
  61.     public InetAddress getInetAddress() {
  62.         return conn.getInetAddress();
  63.     }
  64.  
  65.  
  66.     public int getPort() {
  67.         return conn.getPort();
  68.     }
  69.  
  70.  
  71.     public void WriteLine( String line ) throws IOException {
  72.         sout.writeShort( line.length() );
  73.         sout.writeBytes( line );
  74.         sout.flush();
  75.     }
  76.     
  77.     
  78.     public String ReadLine() {
  79.         String line;
  80.         try {
  81.             int length = sin.readUnsignedShort();
  82.             byte b[] = new byte[length];
  83.             sin.read( b );
  84.             line = new String( b, 0 );
  85.         } catch (IOException e) {
  86.             close();
  87.             line = null;
  88.         }
  89.         return line;
  90.     }
  91.  
  92. }
  93.